package dongze.com.ckdj.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceFragment;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import dongze.com.ckdj.R;
import dongze.com.ckdj.databinding.FragmentProcessableBinding;
import dongze.com.ckdj.databinding.model.ProcessingModel;

/**
 * Created by fanqwz on 2017/8/14.
 */

public class ProcessablePreferenceFragment extends PreferenceFragment {
    ProcessingModel processingModel = new ProcessingModel();
    int processCount = 0;
    Handler handler;
    FragmentProcessableBinding binding;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler(Looper.getMainLooper());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_processable, container, false);
        binding = DataBindingUtil.bind(root);
        binding.setProcessing(processingModel);
        ((ViewGroup) root.findViewById(R.id.stub)).addView(super.onCreateView(inflater, container, savedInstanceState));
        return root;
    }

    public void doProcessing() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                processCount++;

                if (processCount > 0) {
                    binding.getRoot().setEnabled(false);
                    processingModel.visible.set(true);
                }
            }
        });
    }

    public void finishProcessing() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                processCount--;

                if (processCount <= 0) {
                    binding.getRoot().setEnabled(true);
                    processingModel.visible.set(false);
                }
            }
        });
    }
}
